<template>
    <el-container style="min-height: 100vh">
      <el-aside width="220px" style="background: #fff; box-shadow: 2px 0 8px #f0f1f2">
        <div style="padding: 16px; text-align: center; font-weight: bold; font-size: 18px">历史记录</div>
        <el-button type="info" icon="el-icon-document" style="margin: 16px" @click="goHistory" plain>查看全部</el-button>
        <el-button type="danger" icon="el-icon-switch-button" style="margin: 16px" @click="logout" plain>退出登录</el-button>
      </el-aside>
      <el-container>
        <el-header style="background: #fff; box-shadow: 0 2px 8px #f0f1f2; padding: 0 24px; font-size: 20px; font-weight: bold">
          智能问答助手
        </el-header>
        <el-main style="background: #f0f2f5; padding: 24px">
          <div style="max-width: 700px; margin: 0 auto">
            <!-- 修改为对话框形式 -->
            <div ref="chatContainer" style="height: 400px; overflow-y: auto; padding: 16px; background: white; border-radius: 8px; margin-bottom: 24px">
              <div v-for="(item, idx) in chatList" :key="idx" class="message-container">
                <!-- 用户消息气泡 -->
                <div class="user-message">
                  <div class="message-bubble user-bubble">
                    <div class="message-sender">你</div>
                    <div class="message-content">{{ item.question }}</div>
                  </div>
                </div>
                <!-- 助手消息气泡 -->
                <div class="assistant-message">
                  <div class="message-bubble assistant-bubble">
                    <div class="message-sender">助手</div>
                    <div class="message-content">{{ item.answer }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <div style="display: flex; margin-top: 24px">
              <el-input 
                v-model="question" 
                type="textarea" 
                :rows="2" 
                placeholder="请输入你的问题..." 
                style="margin-right: 8px" 
                @keyup.enter="handleSend"
              />
              <el-upload :show-file-list="false" :before-upload="beforeUpload">
                <el-button icon="el-icon-picture" style="margin-right: 8px">图片</el-button>
              </el-upload>
              <el-button type="primary" @click="handleSend" :loading="loading">发送</el-button>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const question = ref('');
const image = ref(null);
const chatList = ref([]);
const loading = ref(false);
const chatContainer = ref(null); // 用于自动滚动
const userId = localStorage.getItem('userId');

const fetchHistory = async () => {
  if (!userId) return;
  try {
    const res = await axios.get(`/api/history/list/${userId}`);
    if (Array.isArray(res.data)) {
      chatList.value = res.data.map(item => ({
        question: item.question,
        answer: item.answer
      }));
      scrollToBottom();
    }
  } catch (e) {
    ElMessage.error('历史记录加载失败');
  }
};

// 自动滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContainer.value) {
      chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
    }
  });
};

onMounted(() => {
  if (!userId) {
    router.push('/login');
    return;
  }
  fetchHistory();
});

const handleSend = async () => {
  if (!question.value) return ElMessage.warning('请输入问题');
  loading.value = true;
  
  // 先添加用户问题到聊天列表
  chatList.value.push({
    question: question.value,
    answer: '思考中...' // 添加加载状态
  });
  
  scrollToBottom();
  
  const formData = new FormData();
  formData.append('userId', userId);
  formData.append('question', question.value);
  if (image.value) formData.append('image', image.value);
  
  try {
    const res = await axios.post('/api/chat/ask', formData);
    if (res.data.success) {
      // 更新最后一条消息的答案
      chatList.value[chatList.value.length - 1].answer = res.data.answer;
    } else {
      chatList.value[chatList.value.length - 1].answer = '回答获取失败';
      ElMessage.error(res.data.error || '提问失败');
    }
  } catch (e) {
    chatList.value[chatList.value.length - 1].answer = '请求失败，请重试';
    ElMessage.error('请求失败');
  }
  
  question.value = '';
  image.value = null;
  loading.value = false;
  scrollToBottom();
};

const beforeUpload = (file) => {
  image.value = file;
  return false;
};

const goHistory = () => {
  router.push('/history');
};

const logout = () => {
  localStorage.removeItem('userId');
  router.push('/login');
};
</script>

<style scoped>
.message-container {
  margin-bottom: 20px;
}

.message-bubble {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 8px;
  margin-bottom: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  position: relative;
}

.user-message {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
}

.user-bubble {
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
}

.assistant-message {
  display: flex;
  justify-content: flex-start;
}

.assistant-bubble {
  background-color: #f6f6f6;
  border: 1px solid #e8e8e8;
}

.message-sender {
  font-weight: bold;
  font-size: 12px;
  margin-bottom: 4px;
  color: #666;
}

.message-content {
  line-height: 1.5;
  white-space: pre-wrap;
}
</style>